package masterjava.common.shared.entity;

import masterjava.common.shared.HasId;

import javax.persistence.*;

/**
 * Base entity for all other
 * <p/>
 * Importent: cause Hibernate treat java transient as @Transient when AccessType.FIELD,
 * use everywhere AccessType.PROPERTY.
 * In all entities only getters must be annotated, mix do not allowed by Hibernate
 */

@MappedSuperclass
@Access(AccessType.PROPERTY)
public abstract class BaseEntity implements GenericEntity<Long>, HasId {

    private Long id;

    @Column(name = "ID")
    @Id
    @GeneratedValue
    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public void prepareToPersist() {
    }

    @Override
    public boolean equals(Object o) {
        BaseEntity be = (BaseEntity) o;
        if (id == null || o == null || be.id == null) {
            return false;
        }
        return id.longValue() == be.id.longValue();
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }

    @Override
    public String toString() {
        return getClass().getName() + ":" + id;
    }

    protected static Long evalEntityId(BaseEntity entity) {
        return entity == null ? null : entity.getId();
    }
}
